#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/12/5 10:21
# @Author  : Aries
# @Site    : 
# @File    : waterPixelsMask.py.py
# @Software: PyCharm

import os
import sys
import glob
import numpy as np


def wpMask(basedir):
    """
    #param basedir 存放哨兵2的L2级产品的文件夹
    """
    #找出每景哨兵影像
    s2_folders = [item for item in os.listdir(basedir)
                if not os.path.basename(item).endswith('BIAS')]
    #遍历找到每一景大气校正后分辨率20米的文件夹
    for s2_folder in s2_folders:
        # B1重采样
        B1_60m = glob.glob('{}\\{}\\**\\*B01_60m.jp2'.format(basedir, s2_folder), recursive=True)[0]
        B1_20m = "{}_B01_20m.jp2".format(B1_60m[:-12])
        cmd_res = "gdal_translate -tr 20 20 {} {}".format(B1_60m, B1_20m)
        os.system(cmd_res)
        # # 将参与运算的一个波段(B2)转换为浮点类型，保存在临时文件夹
        B2_20m = glob.glob('{}\\{}\\**\\*B02_20m.jp2'.format(basedir, s2_folder), recursive=True)[0]
        # B2_20m_f = "{}\\BIAS\\floattmp\\{}_float.jp2".format(basedir, os.path.split(B2_20m)[1][:-4])
        # cmd_float = "gdal_translate -ot Float32 {} {}".format(B2_20m, B2_20m_f)
        # os.system(cmd_float)
        # 水体掩膜
        B3_20m = glob.glob('{}\\{}\\**\\*B03_20m.jp2'.format(basedir, s2_folder), recursive=True)[0]
        B8a_20m = glob.glob('{}\\{}\\**\\*B8A_20m.jp2'.format(basedir, s2_folder), recursive=True)[0]
        B11_20m = glob.glob('{}\\{}\\**\\*B11_20m.jp2'.format(basedir, s2_folder), recursive=True)[0]
        B12_20m = glob.glob('{}\\{}\\**\\*B12_20m.jp2'.format(basedir, s2_folder), recursive=True)[0]
        CMD = 'python P:\\AoiSoft\\ANACONDA\\Scripts\\gdal_calc.py' \
              ' -A {} -B {} -C {} -D {} -E {} -F {} --format=GTiff ' \
              '--outfile={}\\BIAS\\watermask\\{}_water_mask.tif ' \
              '--calc="((1.0*D+1.0*E+1.0*F)-(1.0*A+1.0*B+1.0*C))/(1.0*D+1.0*E+1.0*F+1.0*A+1.0*B+1.0*C+1e-9)<0"'\
            .format(B1_20m, B2_20m, B3_20m, B8a_20m, B11_20m, B12_20m, basedir, s2_folder)
        os.system(CMD)
    pass


if __name__ == "__main__":
    wpMask("D:\\tmp")